import { create } from "zustand"
import { immer } from "zustand/middleware/immer"
import { devtools } from "zustand/middleware"
import { persist, createJSONStorage } from "zustand/middleware"

interface User {
  gourd: {
    oneChild: string,
    twoChild: string,
    threeChild: string,
    fourChild: string,
    fiveChild: string,
    sixChild: string,
    sevenChild: string
  },
  age: number
  updateGourd: () => void
}

const log = (config) => (set, get, api) => config((...args) => {
  console.log('before', get(), api);
  set(...args)
  console.log('after', get(), api);

}, get, api)

const useUserStore = create<User>()(
  immer(
    persist(
    devtools(
      log(
        (set, get) => ({
          gourd: {
            oneChild: '大娃',
            twoChild: '二娃',
            threeChild: '三娃',
            fourChild: '四娃',
            fiveChild: '五娃',
            sixChild: '六娃',
            sevenChild: '七娃',
          },
          age: 20,
          updateGourd: () => {
            // set((state) => ({
            //   gourd: {
            //     ...state.gourd,
            //     oneChild: `${state.gourd.oneChild}-超进化`,
            //   }
            // }))

            // immer写法
            set(state => {
              state.gourd.oneChild = `${state.gourd.oneChild}-超进化`
            })
          }
        }))
      ),
      {
        name: 'user',
        storage: createJSONStorage(() => localStorage),
        partialize: (state) => ({
          gourd: state.gourd,
          age: state.age
        })
      }
    ) 
  )
)

export default useUserStore